#!/usr/bin/env python3.2
"""WikiBase parent class for pydblite databases

Initialise WikiBase with backend = 'sqlite' or 'base
according to the backend desired.
"""

import os
from datetime import datetime

def _log(self, *args):
    import sys
    for arg in args:
        sys.stderr.write('%s\n' % arg)

class WikiBase(object):
    default_record = {
        'name':None,
        'content':'',
        'admin':None,
        'nbvisits':0,
        'created':datetime.now(),
        'version':0,
        'lastmodif':datetime.now()
        }
    def __init__(self,path,backend='sqlite'):
        if backend == 'sqlite':        
            self._init_sqlite(path)
        else:
            self._init_base(path)
    def _init_base(self, path):
        from PyDbLite import PyDbLite
        self.db = PyDbLite.Base(path)
        self.db.create('name','content','admin','nbvisits','created',
            'version','lastmodif',mode="open")
        self.db.create_index('name')
    def _init_sqlite(self, path):
        from PyDbLite.SQLite import Database, Table
        conn = Database(path)
        table = Table('wiki', conn)
        table.create(
            ('name','TEXT'),
            ('content','TEXT'),
            ('admin','INTEGER'),
            ('nbvisits','INTEGER'),
            ('created','BLOB'),
            ('version','INTEGER'),
            ('lastmodif','BLOB'),
            mode="open")
        table.is_datetime('created')
        table.is_datetime('lastmodif')
        self.db = table
    def get(self,name):
        """Get a page record
        Return an empty record if the page does not exist
        """
        records = self.db(name=name)
        if records:
            return records[0]
        else:
            record = self.default_record.copy()
            record['name'] = name
            return record
    def put(self,record,**kw):
        """Update or insert a page record
        record['__id__'] is not defined if the record is new
        """
        if '__id__' in record:
            self.db.update(record,**kw)
        else:
            record.update(kw)
            self.db.insert(**record)
        self.db.commit()
    def delete(self,name):
        self.db.delete(self.db(name=name))
        self.db.commit()
    def iter_pages(self,orderby='name',desc=False,limit=0):
        _log('iter_pages')
        items = [(r[orderby],r['__id__']) for r in self.db]
        items.sort()
        if desc:
            items.reverse()
        if limit > 0:
            items = items[:limit]
        for val,_id in items:
            yield self.db[_id]
    def pagelist(self,orderby='name',desc=False,limit=0):
        return [p for p in self.iter_pages(orderby=orderby,desc=desc,limit=limit)]

if __name__ == "__main__":
    db = WikiBase('test.sqlite',backend='sqlite')
    page = db.get('TestPage')
    db.put(page, content='Updated content',nbvisits=page['nbvisits']+1)
    page = db.get('TestPage')
    print(page)
    